const superagent = require('superagent')
const charset = require('superagent-charset')
const cheerio = require('cheerio')
charset(superagent)

const baseUrl = 'http://www.win4000.com/zt/rili.html'

module.exports = function (req, res) {
    //设置请求头
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header('Access-Control-Allow-Headers', 'Content-Type');

    superagent.get(baseUrl)
        .charset('UTF-8')
        .end(async function(err, sres) {
            var items = []
            if (err) {
                res.json({code: 400, msg: err, sets: items})
                return
            }
            let $ = cheerio.load(sres.text)
            $('div.main div.main_cont div.w1180 div.Left_bar div.list_cont div.tab_tj div.tab_box div ul.clearfix li a').each(function() {
                let title = $(this).attr('title')
                let href = $(this).attr('href')
                let src = $(this).find('img').attr('data-original')
                items.push({
                    title: title,
                    href: href,
                    src: src
                });
            })
            // res.json({code: 200, msg: 'success', data: items})

            var itemList = []
            for (let index = 0; index < items.length; index++) {
                const element = items[index];
                try {
                    let imgData = await fetchItem(element.href)
                    itemList.push(imgData)
                } catch (error) {
                    console.log(error)
                }
            }
            res.json({code: 200, msg: 'success', data: itemList})
        })
}